/**
 * @file
 * @description axios二次封装
 */

import axios from "axios";
import { Message } from 'element-ui'
import store from 'store'


axios.defaults.baseURL = '/api'
axios.defaults.timeout = process.env.VUE_APP_TIMEOUT

/**
 * 请求拦截器
 */
axios.interceptors.request.use(config => {
  config.headers.Authorization = store.getters.token
  return config
}, error => Promise.reject(error))

/**
 * 响应拦截器
 */
axios.interceptors.response.use(response => {
  const { data } = response.data 
  return data
}, error => {
  const msg = error.toString();
  if (msg === 'Network Error') {
    Message.error('网络错误,请检查网络是否连通')
    return Promise.reject(error)
  }
  if (msg === 'Timeout') {
    Message.error('请求超时,请稍后再试')
    return Promise.reject(error)
  }
  const { status } = error.response
  switch (status) {
    case 401:
      Message.error('登录过期，请重新登录');
      // 清空token
      break;
    case 404:
      const { msg } = error.response.data 
      Message.error(msg || '接口不存在')
    case 500:
      Message.error('服务器内部错误')
      break;
    default:
      Message.error('未知错误')
      break;
  }
  return Promise.reject(error)
})


export default axios